//
//  LoginViewController.m
//  ActiveDeck
//
//  Created by Chiao-Wei Liu on 2011/4/4.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "LoginViewController.h"
#import "HttpRequest.h"
#import "GDataXMLNode.h"



@implementation LoginViewController



@synthesize Txt_Email, Txt_Pass , AuthNode, loginXML, loginSuccess , NewUserVC,cont_UserName, environment;

-(id)delegate
{
	return _delegate;
}

-(void)setDelegate:(id)delegate
{
	_delegate = delegate;
}

#pragma mark -
#pragma mark Catch Keyboard Event


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == Txt_Email) {
        [Txt_Pass becomeFirstResponder];
    } else if (textField == Txt_Pass) {
        [Txt_Pass resignFirstResponder];
        [self loginPress];
    }
    return YES;
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if(NewUserVC.createSuccess)
    {
        environment = NewUserVC.environment;
        
        Txt_Email.text = environment.username;
        Txt_Pass.text = environment.password;
        
        [self loginPress];
    }
}

-(IBAction)createNewUser
{
    NewUserVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:NewUserVC animated:YES];
}

-(IBAction)cancelPress
{
    if([self respondsToSelector:@selector(presentingViewController)])
        [self.presentingViewController dismissModalViewControllerAnimated:YES];
    else 
        [self.parentViewController dismissModalViewControllerAnimated:YES];
}

/// <summary>
/// Action for the Login Button Press
/// </summary>
-(IBAction)loginPress
{    
    //Set the AD_Environment object properties
    NSMutableString *emailText = [[NSMutableString alloc] initWithString:Txt_Email.text];
    NSMutableString *psswdText = [[NSMutableString alloc] initWithString:Txt_Pass.text];
    [environment setAuthenticationUsername:[emailText copy] AndPassword:[psswdText copy]];
    [_delegate setTheEnvironment:environment];
    
    [emailText release];
    [psswdText release];
    
    loginXML = environment.getAuthentication;
    
    HttpRequest *configRequest = [HttpRequest alloc];
    configRequest.showAlert = TRUE;
    
    //Insure the user can be logged in
    NSString *TestUserPost = [NSString stringWithFormat:@"%@/Config.svc/Login", [HttpRequest GetSvcURL]];
    
    NSString *userXMLString = [configRequest XML_PostRequest:loginXML urlString:TestUserPost];
    
    if([userXMLString isEqualToString:@"Error"])
    {
        UIAlertView *alertMSG = [UIAlertView alloc];
        alertMSG = [alertMSG initWithTitle:@"Login Failure"
								   message:@"Please Enter Correct Username and Password."
								  delegate:self 
						 cancelButtonTitle:@"OK" 
						 otherButtonTitles:nil];
		
		[alertMSG show];
        [alertMSG release];
    }
    else
    {
        NewUserVC.createSuccess = FALSE;
        loginSuccess = true;
        
        if([self respondsToSelector:@selector(presentingViewController)])
            [self.presentingViewController dismissModalViewControllerAnimated:YES];
        else
            [self.parentViewController dismissModalViewControllerAnimated:YES];
    }    
}

-(void) BuildXMLAuth
{
	GDataXMLElement *Authentication = [GDataXMLNode elementWithName:@"Authentication"];
	GDataXMLNode *UserName = [GDataXMLNode attributeWithName:@"UserName" stringValue:Txt_Email.text];
	GDataXMLNode *Password = [GDataXMLNode attributeWithName:@"Password" stringValue:Txt_Pass.text];
    GDataXMLNode *PlainText = [GDataXMLNode attributeWithName:@"Plaintext" stringValue:@"True"];
    
	[Authentication addChild:UserName];
	[Authentication addChild:Password];
    [Authentication addChild:PlainText];
	
	
	GDataXMLDocument *document = [[[GDataXMLDocument alloc] initWithRootElement:Authentication] autorelease];
	NSData	*xData = document.XMLData;
	loginXML = [[NSString alloc] initWithData:xData encoding:NSUTF8StringEncoding];
    cont_UserName = [[NSString alloc] initWithFormat:@"%@", [[environment.username stringByReplacingOccurrencesOfString:@"@" withString:@"_"] stringByReplacingOccurrencesOfString:@"." withString:@"_"]];
	
	AuthNode = [[GDataXMLElement alloc]init];
	AuthNode = [Authentication copy];
}


- (void)dealloc
{
    [Txt_Email release];
    [Txt_Pass release];
    [AuthNode release];
    [loginXML release];
    [cont_UserName release];
    [NewUserVC release];
    [environment release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    NewUserVC = [NewUserViewController alloc];
    [NewUserVC setEnvironment:environment];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
	return NO;
}

@end
